<!--成片配置 / 采集配置 —— 抽屉 -->
<template>
  <el-drawer
    size="55%"
    :title="hideType==1 ? '成片配置' : '采集配置' "
    :visible="visible"
    @close="updateVisible(false)">
    <el-form
      :show-message="false"
      :hide-required-asterisk="false"
      ref="form"
      :rules="rules"
      :model="form"
      label-width="110px"
      @keyup.enter.native="submit"
      @submit.native.prevent
    >
      <div class="padding20">
        <!--成片管理 区分end-->
        <el-form-item label="请选择文件夹" prop="chipConfiguration.folderId">
          <el-select
            v-model="form.chipConfiguration.folderId"
            placeholder="请选择文件夹"
            class="ele-block"
            clearable
            @clear="see()"
          >
            <div v-for="(i,j) in data" :key="j">
              <el-option :label="i.name" :value="i.id" />
            </div>
          </el-select>
          <div>选择一个文件夹，如你暂无文件夹，可点击 <span class="blue pointer" @click="openNewFile">创建文件夹</span></div>
        </el-form-item>
        <el-form-item label="请选择摄像头" class="check-star" prop="cameraConfigurations"
                      :rules="!form.cameraConfigurations  ? { required: true, message: '请选择摄像头', trigger: ['blur','change']} : {required: false}">
          <!--表格下拉——多选-->
          <demo-multiple ref="multiple" @getList="getList" />
          <!--<span>注明：选择空闲中，而且没有过期，并且是在线中的摄像头</span>-->
        </el-form-item>
        <el-form-item label="摄像头配置" class="set-class check-star">
          <camera-set ref="cameraSet" @getListIds="getListIds" @allDianShu="allDianShu"></camera-set>
        </el-form-item>
        <el-form-item label="采集时间段" class="m-top10 check-star" prop="time"
                      :rules="!form.time  ? { required: true, message: '请选择采集时间段', trigger: ['blur','change']} : {required: false}">
          <!--采集时间段可选多个-->
          <!--<el-time-select
            style="width: calc(50% - 10px)"
            @change="startChanges"
            placeholder="起始时间"
            v-model="startTime"
            :picker-options="{
               start: '08:00',
               step: '00:30',
               end: '24:00'
               }">
          </el-time-select>
          <el-time-select
            style="width: calc(50% - 10px)"
            class="m-left20"
            @change="endChanges"
            placeholder="结束时间"
            v-model="endTime"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '24:00'
            }">
&lt;!&ndash; minTime: startTime,&ndash;&gt;
          </el-time-select>-->
          <el-button class="width100" @click="timeSlot">+点击选择采集时间段</el-button>
          <div>提示：建议选择店铺2~3个热闹时间段 </div>
          <div v-show="selTimeList.length>0">已选择时间段：【{{selTimeList.join(',')}}】</div>
        </el-form-item>
        <!--成片管理 区分start-->
        <div v-if="hideType==1">
          <el-form-item label="背景音乐类型" class="check-star">
            <el-select
              clearable
              v-model="musicType"
              placeholder="请选择背景音乐类型"
              class="ele-fluid"
              @change="changeCategory"
            >
              <el-option :label="i.name" :value="i" v-for="(i,j) in mcList" :key="j" />
            </el-select>
          </el-form-item>
          <el-form-item label="背景音乐" class="check-star" prop="camerabgm"
                        :rules="!form.camerabgm  ? { required: true, message: '请选择背景音乐', trigger: ['blur','change']} : {required: false}" >
            <div class="s-musiz-class" :style="!form.camerabgm && hint  ?'border:1px solid #ff4d4f;' : ''">
              <div class="flex-align-center m-bottom5">
                <img src="@/assets/music.png" v-show="bgmName" />
                <el-select
                  v-model="bgmName"
                  placeholder="请选择背景音乐"
                  class="ele-fluid music-select-class"
                  @change="getMusics"
                >
                  <el-option :label="i.title" :value="i" v-for="(i,j) in musicLists" :key="j" />
                </el-select>
              </div>
            </div>
          </el-form-item>

          <el-row class="padding">
            <el-col :span="12">
              <el-form-item label="背景音量" prop="name">
                <el-slider
                  class="m-left20 slider-class width90"
                  :max="10"
                  input-size="mini"
                  v-model="form.cameravolumeconfiguration.bgmVolume"
                  show-input>
                </el-slider>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="视频原声" prop="name">
                <el-slider
                  class="m-left20 slider-class width90"
                  :max="10"
                  input-size="mini"
                  v-model="form.cameravolumeconfiguration.videoVolume"
                  show-input>
                </el-slider>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="解说设置" prop="name"  class="check-star">
            <el-radio-group v-model="form.montageType" @input="explainSet">
              <el-radio :label="1">自己上传</el-radio>
              <el-radio :label="2">AI配音</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="form.montageType==1" class="no-check-star">
            <el-form-item label="全程解说" prop="cameraexplain"
                          :rules="!form.cameraexplain  ? { required: true, message: '请上传全程解说', trigger: ['blur','change']} : {required: false}">
              <!--:before-upload="beforeAvatarUpload"-->
              <el-upload
                class="el-upload-class"
                :show-file-list="false"
                :action="ossUrl"
                accept=".mp3,.m4a,.aac"
                :multiple="false"
                :on-change="uploadClick"
                :file-list="fileList">
                <el-button class="width100">+点击上传全程解说</el-button>
              </el-upload>
              <!--时长需（动态计算）-->
              <div v-if="timeLength">提示：建议时长最大{{timeLength}}秒</div>
            </el-form-item>
            <!--可多个上传 -->
            <el-form-item label="全程解说" v-if="explanList.fileName"
            >
              <!--<div class="d-musiz-class">
                <div class="flex-align-center m-bottom10" v-for="(i,j) in explan" :key="j">
                  <img src="@/assets/music.png" />
                  {{i.bgmName ? i.bgmName : i.fileName}}
                </div>
              </div>-->
              <div class="d-musiz-class">
                <div class="flex-between m-bottom5">
                  <div class="flex-align-center">
                    <img src="@/assets/music.png" />
                    {{explanList.bgmName ? explanList.bgmName : explanList.fileName}}
                  </div>
                  <el-button @click="clearExplan" icon="el-icon-close"></el-button>
                </div>
              </div>
              <el-slider
                class="m-slider"
                input-size="small"
                :max="10"
                v-model="form.cameravolumeconfiguration.audioVolume"
                show-input>
              </el-slider>
            </el-form-item>
          </div>
          <div v-if="form.montageType==2">
            <el-form-item label="AI配音"  prop="cameravoiceconfiguration"
                          :rules="!form.cameravoiceconfiguration  ? { required: true, message: '请选择Ai配置', trigger: ['blur','change']} : {required: false}">
              <div class="flex-align-center">
                <div class="ai-class pointer" :class="videoName ? 'ai-blue' : 'ai-btn'" @click="aiSet">{{videoName ? videoName : 'AI配音设置' }}</div>
              </div>
              <el-slider
                class="m-slider"
                input-size="small"
                :max="10"
                v-model="form.cameravolumeconfiguration.audioVolume"
                show-input>
              </el-slider>
            </el-form-item>
            <div v-for="(item, index) in form.cameraTexts" :key="index">
              <!--校检表单-->
              <el-form-item :label="'全程解说'+(index+1)" :prop="'cameraTexts.'+index+'.content'" :rules="rules.contents">
                <div style="display:flex;">
                  <el-input
                    type="textarea"
                    :maxLength="300"
                    :rows="2" v-model="item.content" placeholder="请输入文本" class="e-input" @input="changeMney(item,index)" />
                  <el-button class="btn-position" @click="add" v-if="0==index" >+</el-button>
                  <el-button class="btn-position" @click="subtract(index)" v-else >-</el-button></div>
              </el-form-item>
            </div>
          </div>
        </div>

        <!--成片管理 区分end-->
        <el-form-item label="采集天数" prop="chipConfiguration.collectionDays">
          <el-select
            clearable
            v-model="form.chipConfiguration.collectionDays"
            placeholder="请选择采集天数"
            class="ele-fluid"
          >
            <el-option label="1天" :value="1" />
            <el-option label="2天" :value="2" />
            <el-option label="3天" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用点数" class="delInput check-star">
          <el-input
            type="number"
            disabled
            v-model.number="form.chipConfiguration.usageDays"
            placeholder="请输入使用点数"
            clearable
          />
          <div>当前剩余<span class="red">{{points}}</span>点</div>
        </el-form-item>
      </div>
    </el-form>
    <div class="flex-end m-bottom20">
      <el-button round @click="resetting">重置</el-button>
      <el-button type="primary" class="margin20" round  @click="confirm()" :loading="loading">提交</el-button>
    </div>
    <!--‘ 采集时间段 ’抽屉-->
    <time-modal ref="timeShow" :oldList="selTimeList" @timeClick="timeClick"></time-modal>
    <!--旁白弹框-->
    <narration
      ref="narrationShow" @aiClick="aiClick"></narration>
    <!--创建文件夹-->
    <folder-add
      ref="folderAdd"
      :visible.sync="folderAddVisible"
      :parent-id="0"
      @done="onDone"
    ></folder-add>
  </el-drawer>
</template>

<script>
  // import 方式
  import moment from 'moment';
  import timeModal from '../components/time-modal.vue'
  import {registerAssetsMedia, userOssSignature, ossUpdate2} from "@/api/creatCenter/material";
  import {getToken} from "@/utils/token-util";
  import DemoMultiple from '../../automaticSlicing/components/demo-multiple.vue';
  import axios from "axios";
  import Narration from "@/views/lncomingManagement/cameraManage/collectMaterials/components/narration";
  import CameraSet from "@/views/lncomingManagement/cameraManage/collectMaterials/components/camera-set";
  import {getDianShu} from "@/api/system/user";
  import FolderAdd from "../../automaticSlicing/components/folder-add";
  import {createFragmentedTask, publishTask, queryOemPoint,largeAccountToken} from "@/api/lncomingManagement/cameraManage"
  import {musicCollect, musicList} from "@/api/lncomingManagement/music";
  import {mc} from "@/utils/js/mc_list";


  export default {
    components:{FolderAdd, CameraSet, Narration, DemoMultiple, timeModal},
    name: "btn-configuration",
    props:{
      mcList: Array,  // 音乐类型list
      musics: Array,  // 音乐列表list
      // 文件列表数据
      data: Array,
      visible:Boolean
    },
    computed: {
      // 计算‘全程解说’时长——（摄像头配置，每个素材时长集合++）
      timeLength() {
        let timeLength = 0;
        if(this.mulitpleList.length>0){
          for(let i=0;i<this.mulitpleList.length;i++){
            let num = this.mulitpleList[i].materialDuration ? Number(this.mulitpleList[i].materialDuration) : 0
            timeLength+=num
          }
        }
        return timeLength;
      }
    },
    data(){
      const defaultForm = {
        // 文件夹id/天数/点数
        chipConfiguration: {
          folderId:'',
          usageDays:0
        },
        // 背景音量/视频原声/全程解说 音量
        cameravolumeconfiguration:{
          bgmVolume:0,  //背景音量
          audioVolume:0,  //旁白音量
          videoVolume:0,  //视频音量
          merchantId: this.$store.state.user.info.merchantId
        },
        // 背景音乐参数名
        camerabgm:'',
        cameraConfigurations:'', // 摄像头列表
        cameraexplain:'',   //全程解说参数名
        cameravoiceconfiguration:'', // AI配音设置
        // 解说音频设置需要
        montageType:1,
        // 口播音频需要（摄像头文本）
        cameraTexts:[{
          content:''
        }]
      }
      return{
        defaultForm,
        hint:'',
        loading:false,
        videoName:'',
        folderAddVisible:false,
        mulitpleList:[],
        value:0,
        fileList: [],
        // form:{ ...defaultForm },
        form:JSON.parse(JSON.stringify(defaultForm)),

        rules: {
          // 全程解说
          /*cameraexplain: {
            mediaId: [
              {
                required: true,
                message: '请上传全程解说',
                trigger: 'blur'
              }
            ],
          },*/

          contents: [
            { required: true,
              message: '请输入全程解说文本(限制最大300字）',
              trigger: 'blur' }
          ],
          chipConfiguration:{
            // 文件夹
            folderId: [
              {
                required: true,
                message: '请选择文件夹',
                trigger: 'blur'
              }
            ],
            collectionDays: [
              {
                required: true,
                message: '请选择采集天数',
                trigger: 'blur'
              }
            ],
          },

          activityName: [
            {
              required: true,
              message: '请输入活动名称',
              trigger: 'blur'
            }
          ],
        },
        // 采集时间段 start
        startTime: '',
        endTime: '',
        selTimeList:[],  // 时间段list
        uploadAccount:[],
        // 日期列表 (年月日)
        dateList:[],
        // 采集时间段 end
        points:0,  // 点数
        singleNum: 0,
        /*'全程解说'音频 start*/
        // musicList:[],
        explanList:{},
        /*'全程解说'音频 end*/

        // 背景/热榜音乐 start

        musicType:'', // 背景音乐类型
        bgmName:'',  // 选择的音乐名称
        bgmUrl:'',  // 选择的音乐url地址，用于上传阿里云
        selectIndex: 0,
        musicLists:this.musics, // 音乐列表list
        // end

        tableSuccess:1,
        hideType:1, // 1:自动成片 2:采集素材
        oemPoint:0, // oem代理发布点数
      }
    },
    methods:{
      show(hideType){


        /*this.largeCS()*/  //测试，未使用

        this.hideType=hideType
        console.log('进入show===========this.mcList',this.mcList,'this.defaultForm',this.defaultForm)
        if(this.mcList&& this.mcList.length>0){
          this.changeCategory(this.mcList[0])
        }
        this.$emit('done');  // 调用接口，刷新文件夹数据
        this.queryPoints()
      },
      // cs小程序largeAccountToken
      largeCS(){
        largeAccountToken()
          .then((msg) => {
            console.log('msg',msg)
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      // 查询点数（需对接）
      queryPoints(){
        // 查询可用点数
        getDianShu({
          id: this.$store.state.user.info.merchantId
        }).then((msg) => {
          console.log('msg',msg)
          if(msg){
            this.points= msg.counts;  // 剩余点数
          }
        })
          .catch((e) => {
            this.$message.error(e.msg);
          });

        // 查询oem，发布视频点数
        queryOemPoint({
          id: this.$store.state.user.info.merchantId
        }).then((data) => {
          console.log('发布频点数data',data)
          this.oemPoint=data.releaseVideos
        })
          .catch((e) => {
            this.$message.error(e);
          });
      },

      // 音乐start
      async changeCategory (item) {
        this.musicType=item.name
        this.bgmName=''
        this.form.camerabgm='' //用于校检

        this.musicLists = []
        let mcid = item.id_str
        // 热榜音乐接口，需要加username
        let musics = await musicList(mcid,this.$store.state.user.info.username)
        musics && musics['music_list'] ? this.musicLists = musics['music_list'] : void 0
        console.log("this.musicLists",this.musicLists)
      },
      getMusics(e){
        console.log('getMusics===e',e)
        this.bgmName=e.title //用于校检
        this.form.camerabgm=1
        this.bgmUrl=e.play_url.uri
      },
      // 音乐end
      // 视频原声
      sliderClick(e){
        console.log("视频原声e",e)
      },
      // 打开‘创建文件夹’ 弹框
      openNewFile(){
        this.folderAddVisible = true;
        this.$nextTick(()=>{
          this.$refs['folderAdd'].show()
        })
      },
      // 重置
      resetting(){
        this.saveClear()
      },

      // 计算秒数列表总数据—— 暂无可用
      counts(){
        /*
        先设置默认配置
        * 设备  2_divice
        * 时间段 1_timeSlot
        * oem点数为1_oemPoint
        * 使用点数为100_usePoint
        * 1天_day=1
        * */
        let divice = 8,
          timeLength=13,
          timeSlot=1,
          oemPoint=15,
          usePoint=100,
          day=1
        /*
        * 使用点数/oem点数=总采集数量
        * 总采集数量/天数/时间段=一天的单个数据段，需采集数量
        *
        *  */
        /*计算每个时间段，采集的次数*/
        let singerNum=0
        let allUseNum = Math.floor(usePoint/oemPoint)  //向下取整_Math.floor  总采集数量

        let he = (allUseNum)/day/timeSlot   // 计算平均单个时间段的采集次数
        console.log('he',he,'usePoint/oemPoint',allUseNum)
        // 如果计算的采集天数大于半个小时最大采集数，则进入
        // 半小时 1800秒，去除设备总时长，得到最大可循环多少次
        let allNum=1800/timeLength  // 得到100次（单个时间段，半个小时内最多可采集的次数）
        if(he>allNum){
          singerNum = allNum
          // let singerNum = he > allNum ? allNum : he
          console.log("he======",he,'allNum',allNum)
          this.mulitpleList.forEach((item,index) => {
            this.$set(item, "cjNum", singerNum);
          });
        }
        // 计算的采集数小于设备数，则需要进位获取采集数，超过了总采集数，则为0
        else{
          // 如果计算的采集天数大于设备数，则进入  5>2
          if(he>=divice){
            if(he%divice==0){
              singerNum = he/divice
              this.mulitpleList.forEach((item,index) => {
                this.$set(item, "cjNum", singerNum);
              });
            }
            else{
              singerNum = Math.ceil(he/divice)  // 向上取整_Math.ceil
              let csNum = 0
              this.mulitpleList.forEach((item,index) => {
                csNum+=singerNum
                if(csNum>allUseNum){
                  // 104-100=4 多4 singerNum13
                  // 代表是第一次超出，则将剩余数量覆盖singerNum,否则为0
                  if(csNum-allUseNum < singerNum){
                    let num = singerNum - (csNum-allUseNum)
                    this.$set(item, "cjNum", num);
                  }
                  else{
                    this.$set(item, "cjNum", 0);
                  }
                  return
                }
                this.$set(item, "cjNum", singerNum);
              });
              console.log(this.mulitpleList, "mulitpleList333---------",csNum);
            }
          }
          // 1<2
          else{
            console.log('进入小于==')
            singerNum = 1
            let csNum = 0
            this.mulitpleList.forEach((item,index) => {
              csNum+=singerNum
              console.log('csNum',csNum,'singerNum',singerNum,'allUseNum',allUseNum)
              if(csNum>allUseNum){
                // 104-100=4 多4 singerNum13
                // 代表是第一次超出，则将剩余数量覆盖singerNum,否则为0
                if(csNum-allUseNum < singerNum){
                  let num = singerNum - (csNum-allUseNum)
                  this.$set(item, "cjNum", num);
                }
                else{
                  this.$set(item, "cjNum", 0);
                }
                return
              }
              this.$set(item, "cjNum", singerNum);
            });
            console.log(this.mulitpleList, "mulitpleList444---------",csNum);

          }
        }
        /*
        计算时间段秒数
        let singerNum = (usePoint/oemPoint) / day / timeSlot
        console.log("singerNum",singerNum)
        let singerTime='2023-08-11 07:00:00' // 单个时间段开始时间 —— singerNum/2
        let time=10 // 单个摄像头设置时长为10s
        let list=[]
        for(let i=0;i<15;i++){
          let second= moment( singerTime, 'YYYY-MM-DD HH:mm:ss' ).add(time, 's').format('YYYY-MM-DD HH:mm:ss')
          singerTime=second
          console.log('second==========',second)
          list.push(second)
        }
        console.log('list======',list)*/
      },
      clearExplan(){
        this.explanList={}
        this.form.cameraexplain=''  //全程解说参数名(校检赋值)
        this.$message.success('删除成功！')
      },
      getBgm(){
        this.loading=true
        this.bgmUrl=this.bgmUrl.replace(new RegExp('https://', 'g'), 'http://');   // https转http
        console.log("this.bgmUrl",this.bgmUrl)
        // 上传背景音乐并注册媒资
        ossUpdate2(this.bgmUrl,this.$store.state.user.info.username)
          .then((data) => {
            let url=data.msg
            registerAssetsMedia({
              mediaUrl:url,//上传阿里云生成的地址
              mediaType:'audio/mpeg',//文件类型,已固定，如果需动态，可设置
              username:this.$store.state.user.info.username
            })
              .then((mediaData) => {
                console.log("mediaData",mediaData)
                // this.musicList.push(data.data)
                this.form.camerabgm={
                  // url:data.data.mediaUrl,
                  bgmName:this.bgmName,
                  duration:mediaData.data.duration,
                  mediaId:mediaData.data.mediaId

                }
                console.log("this.form.camerabgm============",this.form.camerabgm)
                this.save() // 保存成片配置
              })
              .catch((e) => {
                this.$message.error(e);
                this.loading=false
              });
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      // 提交
      confirm(){
        if(!this.oemPoint){
          this.$message.error('请登录oem账号，设置发布点数！')
          // this.$message.error('请配置该商家oem的发布点数！')
          return
        }
        if(this.points<=0){
          this.$message.error('当前点数为0')
          return
        }
        if(this.form.chipConfiguration.usageDays > this.points){
          this.$message.error('使用点数大于总点数')
          return
        }
        // 查询到oem的点数为空，提示“请登录oem账号，设置发布点数”

        // 校检摄像头
        this.$nextTick(()=>{
          this.$refs['cameraSet'].confirm()
        })
        // 校检表单
        console.log("this.rules222",this.rules)
        this.$refs.form.validate((valid, obj) => {
          console.log('valid',valid,'obj',obj)
          for(let i in obj){
            console.log("i",i)
            console.log("obj=========",obj[i][0].message)
            this.hint=obj[i][0].message
            break
          }
          console.log('this.hint',this.hint,'this.tableSuccess',this.tableSuccess)

          if (valid) {
            setTimeout(()=>{
              console.log('校检===========================================================')
              let cameraHint=this.tableSuccess==1?'请输入摄像头配置内容':''
              console.log("cameraHint",cameraHint,'this.tableSuccess',this.tableSuccess)
              if(cameraHint){
                this.$message.error(cameraHint)
                return
              }
              // this.hideType1.自动成片 2.采集视频（区分菜单栏，分类保存）
              if(this.hideType==1){
                this.getBgm()
              }
              else{
                this.form.cameraTexts=[]
                this.form.camerabgm={}
                this.form.cameraexplain={}
                this.form.cameravoiceconfiguration={}
                this.form.cameravolumeconfiguration={}
                this.loading=true
                this.save() // 保存成片配置
              }
            },500)
          } else {
            console.log("进入非空提示",valid,'22',this.form)
            this.$message.error(this.hint)
            return false;
          }
        });
      },
      save(){
        // 保留两个需要的字段 deviceSerial(序列号)
        /*this.musicList = this.musicList.map(({mediaId,fileName,duration})=>{
          return {mediaId,bgmName:fileName,duration};
        })*/

        // this.form.cameraexplain=this.explanList   //全程解说参数名
        console.log("this.mulitpleListaaaaaaaaaaaaaaaaaaaaaaaa",this.mulitpleList,'this.explanList',this.explanList,)
        // this.form.cameraConfigurations=this.mulitpleList  // 摄像头列表
        console.log('保存this.form111==========', this.form)

        delete this.form.time
        // montageType: 1_自己上传 2_AI配音
        // if(this.musicList>0 && this.from.montageType==1){
        if(this.form.montageType==2 && this.hideType==1){
          delete this.form.cameraexplain
        }
        if(this.form.montageType==1 && this.hideType==1){
          delete this.form.cameravoiceconfiguration
          this.videoName=''
        }
        Object.assign( this.form, {
          types:this.hideType   //1.自动成片 2.采集视频（区分菜单栏，分类保存）
        })
        console.log('保存this.form2222==========', this.form)
        createFragmentedTask(this.form)
          .then((data) => {
            console.log('data',data)
            this.goPublish(data)
          })
          .catch((e) => {
            this.loading=false
            this.$message.error(e);
          });
      },
      goPublish(id) {
        console.log("进入发布任务列表数据===========",id,this.mulitpleList)
        // 清空总数据，重新计算
        this.uploadAccount = []
        const startDate = new Date();
        // 获取后N天日期 ‘发布天数’计算后年月日 dateList:年月日数组
        this.dateList = this.$sun.getLastOrNextFewDateBy(startDate, this.form.chipConfiguration.collectionDays) //form.status 需修改
        // 集合 年月日 + 时分秒
        const timeList = []
        this.dateList.forEach(item => {
          this.selTimeList.forEach(child => {
            timeList.push(item + ' ' + child) // 增加秒,timeList,为选择的日期时间汇总
          })
        })
        // 修改start（需修改）——测试完成，正确，需同步快手/抖音 共4个页面
        let list2 = []
        for (let i = 0; i < this.mulitpleList.length; i++) {
          console.log('this.mulitpleList[i]',this.mulitpleList[i])
          let account = this.mulitpleList[i]
          for (let i = 0; i < timeList.length; i++) {
            var list = {}
            // 发布时间
            let date = timeList[i].split(' ')[0]
            let times = timeList[i].split(' ')[1]
            let startTime = times.split('-')[0]
            let endTime = times.split('-')[1]
            account.startTime = date + ' ' + startTime + ':00'
            account.endTime = date + ' ' + endTime + ':00'
            account.folderId = this.form.chipConfiguration.folderId
            account.chipConfigurationId = id  //
            console.log("account",account)
            for (const key in account) {
              list[key] = account[key]
            }
            console.log("list121111",list)

            list2.push(list)
          }
          this.uploadAccount = list2
        }

        //时间排序
        //prop：对象数组排序的键，
        //align：排序方式，"positive"正序，"inverted"倒序。
        this.uploadAccount.sort(this.$sun.compare('startTime','positive'));
        // (单个采集素材总数量*设备)
        let cyclesNum=Math.floor((this.singleNum*this.mulitpleList.length)/(this.uploadAccount.length)) // 向下取整
        let remainder=(this.singleNum*this.mulitpleList.length)%(this.uploadAccount.length)//取余
        console.log("cyclesNum，remainder",cyclesNum,remainder)
        //  cyclesNum等于1 代表余数不能再次循环了，所有this.uploadAccount不需要重复循环
        if(cyclesNum==1 && remainder<this.mulitpleList.length || !cyclesNum && remainder<this.mulitpleList.length){
          publishTask(this.uploadAccount)
            .then((data) => {
              this.$message.success('提交成功！');
              this.loading=false
              this.updateVisible(false)

            })
            .catch((e) => {
              console.log("e",e)
              this.$message.error(e);
              this.loading=false
            });
          return
        }
        if(this.singleNum*this.mulitpleList.length < this.uploadAccount.length){
          this.$message.error('采集素材总数量不足与遍历时间段')
          return;
        }
        let allList=[]
        for(let i=0;i<cyclesNum;i++){
          console.log('cyclesNum11111111111',cyclesNum)
          for(let j=0;j<this.uploadAccount.length;j++){
            allList.push(this.uploadAccount[j]) ;
          }
        }
        console.log('allList111',allList,'remainder',remainder,'this.mulitpleList.length',this.mulitpleList.length)

        if(remainder>0 && remainder>=this.mulitpleList.length){
          // 剩余采集数量>设备数，则将uploadAccount的数组根据大于的数量push进入
          let csNum=Math.floor(remainder/this.mulitpleList.length) // 向下取整
          let  remainderNum=csNum*this.mulitpleList.length
          console.log('remainderNum',remainderNum)
          for(let index=0;index<this.uploadAccount.length;index++){
            if(index >= remainderNum){
              break;
            }
            allList.push(this.uploadAccount[index]) ;
          }
          console.log('allList222',allList)
        }
        let parms={}
        parms.collectionTask=allList
        publishTask(allList)
          .then((data) => {
            this.$message.success('提交成功！');
            this.updateVisible(false)
            this.loading=false
          })
          .catch((e) => {
            console.log("e",e)
            this.$message.error(e);
            this.loading=false
          });

      },


      // 保存后清除
      saveClear(){
        if(this.mcList&& this.mcList.length>0){
          this.changeCategory(this.mcList[0])
        }
        this.$emit('done');  // 调用接口，刷新文件夹数据
        this.queryPoints()
        // 清除 start
        this.form = JSON.parse(JSON.stringify(this.defaultForm))   // 恢复默认的
        // 清空摄像头表格
        this.$nextTick(()=>{
          this.$refs['multiple'].clearClick()
        })
        // 清除列表数据
        this.mulitpleList= []
        this.$nextTick(()=>{
          this.$refs['cameraSet'].show(this.mulitpleList)
        })
        // 清空旁白设置
        this.$nextTick(()=>{
          this.$refs['narrationShow'].clear()
        })
        this.videoName=''  // 旁白按钮文字清空

        // 删除全程解说
        this.explanList={}
        // 清空‘采集时间段’
        this.selTimeList=[]
        // 清除 end
        // this.form = { ...this.defaultForm }
        // this.form=this.form
      },

      // 解说设置
      explainSet(e){
        console.log('e',e)
        if(e==2){
          this.$nextTick(()=>{
            this.$refs['narrationShow'].show()
          })
        }
      },
      // start
      aiSet(){
        this.$nextTick(()=>{
          this.$refs['narrationShow'].show()
        })
      },
      // 多选表格获取到的list_选择摄像头
      getList(e,type){
        console.log("e,type",e,type)
        // type 1:选择了摄像头  e=选择的摄像头列表
        // type 2：从输入框删除了‘摄像头’设备  e=删除的摄像头id
        if(type==1){
          if(this.mulitpleList.length<1){
            console.log("进入零-1========",e)
            this.mulitpleList= e
          }
          else{
            let list =[]
            console.log("e,mulitpleList",e,this.mulitpleList)
            if(e.length>=this.mulitpleList.length){
              list=this.$sun.arrRemoveRepetition(e,this.mulitpleList)
              list.collectionQuantity=this.mulitpleList[0].collectionQuantity
              console.log("进入非零list,this.mulitpleList",list,this.mulitpleList)
              this.mulitpleList=[...this.mulitpleList,...list]
              console.log("进入非零22222222list,this.mulitpleList",list,this.mulitpleList)
            }
            else{
              // 将旧数组的值处理成id集合
              const oldIds = this.mulitpleList.map(item => item.id)
              // 得到newArr与oldArr不同的值
              const result = e.filter(item => !oldIds.includes(item.id))
              // 打印
              console.log(result) // [{id: 4}]
              let sameList=[]
              sameList=this.$sun.csMethod(this.mulitpleList,e)
              console.log('sameList',sameList)
              console.log(" this.mulitpleList", this.mulitpleList,'sameList',sameList,'result',result,result.length)
              this.mulitpleList=[...sameList,...result]
            }
          }
        }
        else{
          this.mulitpleList= this.mulitpleList.filter((d) => d.id !== e)
        }

        this.form.cameraConfigurations=this.mulitpleList.length>0 ? this.mulitpleList : ''  // 摄像头列表
        this.$nextTick(()=>{
          this.$refs['cameraSet'].show(this.mulitpleList)
        })
      },
      allDianShu(e,singleNum,oemPoint){
        this.oemPoint=oemPoint
        this.$set(this.form.chipConfiguration,'usageDays',e)
        // this.form.chipConfiguration.usageDays= e  // 总点数
        this.singleNum=singleNum  // 单个，采集素材总数量
        console.log('输入采集素材总数量22222222this.this.form.usageDays=======',this.form.chipConfiguration.usageDays)
      },
      getListIds(e,row,type){
        this.tableSuccess=type // 2:成功
        console.log('进入删除返回表格获取到的liste========',e,row,type)
        this.mulitpleList= row
        this.form.cameraConfigurations=this.mulitpleList.length>0 ? this.mulitpleList : ''  // 摄像头列表

        if(e==0){return}
        this.$nextTick(()=>{
          this.$refs['multiple'].clear(e)
        })
      },
      // 文本start
      changeMney(data,index){
        console.log("进入修改=========")
        this.form.cameraTexts[index].content=data.content;
        let arr=[];  //新数组
        this.form.cameraTexts.forEach(item=>{
          arr.push(item);
        })
        this.form.cameraTexts=arr;//相当于返回一个新数组可以触发渲染
        console.log('this.form.cameraTexts',this.form.cameraTexts)

      },
      //  加
      add(){
        let content={content:''}
        this.form.cameraTexts.push(content)
        console.log('this.form.cameraTexts',this.form.cameraTexts,this.form.cameraTexts.length)
      },
      //减
      subtract(index){
        this.form.cameraTexts.splice(index, 1)
        console.log("this.form.cameraTexts",this.form.cameraTexts,this.form.cameraTexts.length)
      },
      // end

      timeSlot(){
        this.$nextTick(()=>{
          this.$refs['timeShow'].show()
        })
      },
      // 采集时间段 抽屉
      timeClick(e){
        this.selTimeList=e
        this.form.time=e
        this.$nextTick(()=>{
          this.$refs['cameraSet'].timeCount(this.selTimeList)
        })
        console.log("采集时间段1111111111e",e)
      },

      /* 暂未使用 start */
      startChanges(e){
        console.log("changes",e)
        /*注：subtract vt. 减去；扣掉，即以前的时间
        add vt. 增加，添加，即将来的时间*/
        this.endTime = moment( e, 'HH:mm' ).add(30, 'm').format('HH:mm')
        console.log(this.endTime);

      },
      endChanges(e){
        console.log("changes",e)
        /*注：subtract vt. 减去；扣掉，即以前的时间
        add vt. 增加，添加，即将来的时间*/
        this.startTime = moment( e, 'HH:mm' ).subtract(30, 'm').format('HH:mm')
        console.log(this.startTime);
      },
      /* 暂未使用 end */

      /* 更新 visible */
      updateVisible(value) {
        if(value==false){
          console.log("进入false======",this.form,'this.defaultForm',this.defaultForm)
          this.saveClear()
          // this.form = { ...this.defaultForm }

        }
        this.$emit('update:visible', value);
      },
      hintClick(){
        if(this.explanList.mediaId){
          this.$message.error('最多上传一条全程解说！可删除重试')
          return
        }
      },
      // 全程解说上传前操作
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 20;
        console.log('全程解说上传前操作this.explanList.mediaId=======',this.explanList.mediaId)
        if(this.explanList.mediaId){
          this.$message.error('最多上传一条全程解说！可删除重试')
          return
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
        }
        return !this.explanList.mediaId && isLt2M;
      },
      // 上传
      uploadClick(file){
        if(this.explanList.mediaId){
          this.$message.error('最多上传一条全程解说！可删除重试')
          return
        }
        console.log("进入点击事件",this.explanList,this.explanList.mediaId)
        this.fileList.push(file)
        this.selectVideo();
      },
      async selectVideo(){
        console.log(" this.fileList", this.fileList)
        if(this.fileList.length < 1) {
          console.log("请选择文件后提交")
          return
        }
        console.log('组件调用2222================================')
        this.data = await userOssSignature()
        let file = this.fileList[0].raw
        console.log(file)
        this.filename=file.name;
        let markIndex=( this.filename).lastIndexOf('.');
        let suffix= this.filename.substring(markIndex)
        let date=new Date().getTime();
        // 构建请求参数
        let param = new FormData()
        param.append("key", this.data.dir + date+suffix)
        param.append("policy", this.data.policy)
        param.append("OSSAccessKeyId", this.data.accessId)
        param.append("success_action_status", '200')
        // param.append("callback",  this.data.callback)     //回调（not)
        param.append("signature", this.data.signature)
        param.append("file", file, file.name)
        param.append('success_action_status', '200')
        let config = {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'x-oss-callback-Authorization': getToken()
          }
        }
        console.log("suffix",suffix)
        axios.post(this.data.host, param, config).then(res => {
          if(res.status==200){
            console.log('this.data.host',this.data.host+'/'+date+suffix)
            let url=this.data.host+'/'+date+suffix;
            let type=file.type;
            console.log('file.type',file.type)
            this.fileList=[]
            this.registerMedias(url,type);
            this.onDone();
          }
          else{
            this.$message.error('上传失败');
          }

        }).catch(err => {
          console.log(err)
        })
      },
      registerMedias(url,type) {
        registerAssetsMedia({
          mediaUrl:url,//上传阿里云生成的地址
          mediaType:type,//文件类型
          username:this.$store.state.user.info.username
        })
          .then((data) => {
            this.$message.success("上传成功！")
            console.log("data",data)
            // this.musicList.push(data.data)
            this.explanList={
              url:data.data.mediaUrl,
              fileName:data.data.fileName,
              duration:data.data.duration,
              mediaId:data.data.mediaId

            }
            console.log("this.explanList============",this.explanList)
            this.form.cameraexplain=this.explanList   //全程解说参数名

            this.onDone();
          })
          .catch((e) => {
            this.$message.error(e.msg);
          });
      },
      // AI配音设置返回
      aiClick(form,name){
        console.log('AI配音设置返回form',form,name)
        this.form.cameravoiceconfiguration=form
        this.videoName=name
      },
      /* 完成刷新列表数据 */
      onDone() {
        this.$emit('done');
      },
    }
  }
</script>

<style scoped lang="less">
  .m-slider{
    margin: 10px 0  0 20px;
  }

  .btn-position{
    margin-left: 20px;
  }
  .ai-class{
    margin: 0 10px 0 0;
    padding: 0 20px;
    border-radius: 5px;
  }

  .ai-blue{
    color: #fff;
    background: #93c7f5;
  }
  .ai-btn{
    color: #606266;
    border: 1px solid #dddddd;
  }

  .ai-btn:hover {
    /*background: rgba(50,62,78, 0.5);*/
    background: #e6f7ff;
    color:#1890ff;
    border: 1px solid #1890ff;
  }
  .ai-blue:hover {
    background: #2d90e8;
  }

  /*隐藏input（type=number)右边的小箭头*/
  /deep/.delInput input::-webkit-outer-spin-button,
  /deep/.delInput input::-webkit-inner-spin-button {
    -webkit-appearance: none!important;
  }
  /deep/.delInput input[type="number"]{
    -moz-appearance: textfield;
  }
  .d-musiz-class{
    border:1px solid #ddd;
    border-radius: 6px;
    padding: 5px 10px 0;
    .m-bottom5{
      margin-bottom: 5px;
    }
    img{
      width: 23px;
      margin-right: 10px;
    }
    button{
      border: none;
      padding: 5px 10px;
      font-size: 16px;
    }
  }

  .s-musiz-class{
    border:1px solid #ddd;
    border-radius: 6px;
    padding: 5px 10px 0 5px;
    .m-bottom5{
      margin-bottom: 5px;
    }
    img{
      width: 23px;
      margin-left: 5px;
    }
  }
</style>
